angular.module('app').config(function ($stateProvider) {

    $stateProvider.state('app.device-orientation', {
        url         : '/device-orientation',
        label       : '方向传感器',
        controller  : 'app.device-orientation',
        controllerAs: '$ctrl',
        templateUrl : 'view/app/device-orientation/device-orientation.html'
    });
}).controller('app.device-orientation', function ($ionicPlatform, $timeout) {
    var ctrl = this, watchID;
    ctrl.compasses = [];
    /**
     * CompassHeading
     * - magneticHeading: (number)0~359.99 之间的一个度数
     * - trueHeading: (number)相对于北极的一个 0~359.99 之间的一个度数, 负数表示不能确定
     * - headingAccuracy: (number)reported heading 和 true heading 之间的一个误差
     * - timestamp:
     */

    /**
     * CompassError
     * - CompassError.COMPASS_INTERNAL_ERR(code 0)
     * - CompassError.COMPASS_NOT_SUPPORTED(code 20)
     */
    $ionicPlatform.ready(function () {
        ctrl.get = function () {
            /**
             * navigator.compass.getCurrentHeading(compassSuccess, compassError);
             * - compassSuccess: 会传入一个 CompassHeading 对象的参数
             */
            navigator.compass.getCurrentHeading(function (compassHeading) {
                $timeout(function () {
                    ctrl.currentCompassHeading = compassHeading;
                });
            }, onError);
        };
        ctrl.watch = function () {
            /**
             * var watchID = navigator.compass.watchHeading(compassSuccess, compassError, [compassOptions]);
             *
             * - compassOptions
             *   - frequency: 监听频率, 默认 100 毫秒
             *   - filter: (number)变化的度, 变化的度一旦小余指定的度则不会触发 compassSuccess. 此参数设置后则 frequency 参数就会忽略
             */
            if (watchID) {
                return;
            }
            watchID = navigator.compass.watchHeading(function (compass) {
                $timeout(function () {
                    ctrl.compasses.unshift(compass);
                    if (ctrl.compasses.length > 4) {
                        ctrl.compasses.length = 3;
                    }
                });
            }, onError, {
                frequency: 1000
            });
        };
        ctrl.clearWatch = function () {
            /**
             * navigator.compass.clearWatch(watchID);
             */
            if (!watchID) {
                return;
            }
            navigator.compass.clearWatch(watchID);
            watchID = undefined;
            ctrl.compasses.length = 0;
        };
    });

    function onError(err) {
        alert('onError - ' + err);
    }
});